<style>
    /* 头像悬浮窗样式 */
    :is(.avatar-floating-window) {
        position: fixed;
        top: 8px;
        right: 10px;
        border-radius: 50%;
        width: 60px;
        height: 60px;
        overflow: hidden;
        cursor: pointer;
        transition: top 0.3s ease-in-out;
        z-index: 1000;
    }
    :is(.avatar-floating-window):hover {
        transform: scale(1.1);
    }
    :is(.avatar-floating-window img) {
        width: 100%;
        height: auto;
    }

    /* 屏幕宽度<992px时的样式 */
    @media (max-width: 992px) {
        :is(.avatar-floating-window) {
            position: fixed;
            top: 10px;
            left: 50%;
        }
        :is(.avatar-floating-window):hover {
            transform: scale(1.15);
        }
    }

    /* 屏幕宽度992px-1200px时的样式 */
    @media (min-width: 992px) and (max-width: 1200px) {
        :is(.avatar-floating-window) {
            position: fixed;
            top: 5%; /* 使用百分比 */
            right: 1%; /* 使用百分比 */
            border-radius: 50%;
            width: 40px;
            height: 40px;
            overflow: hidden;
            cursor: pointer;
            transition: none;
            z-index: 1000;
        }
    }

    /* 登录弹窗的样式 */
    :is(.modal) {
        display: none;
        position: fixed;
        z-index: 2;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.4);
        animation: fadeIn 0.5s;
    }
    :is(.modal-content) {
        background-color: #fefefe;
        margin: 15% auto;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        width: 350px;
        max-width: 80%;
        transition: transform 0.3s ease-in-out;
        transform: translateY(-50px);
        opacity: 0;
    }
    :is(.modal-content.show) {
        transform: translateY(0);
        opacity: 1;
    }
    :is(.close) {
        color: #aaa;
        float: right;
        font-size: 60px;
        font-weight: bold;
    }
    :is(.close):hover,
    :is(.close):focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
    }
    /* 动画效果 */
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    /* 输入框美化 */
    :is(input[type="email"]), :is(input[type="password"]) {
        width: calc(100% - 22px);
        padding: 10px;
        margin-bottom: 10px;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
    }
    /* 按钮组 */
    :is(.buttons) {
        display: block;
    }
    /* 每个按钮的样式 */
    :is(.buttons) :is(button) {
        margin-bottom: 10px;
        width: 100%;
        padding: 10px;
        border: none;
        border-radius: 4px;
        background-color: #222;
        color: white;
        font-size: 16px;
        cursor: pointer;
        transition: background-color 0.3s;
    }
    :is(.buttons) :is(button):hover {
        background-color: #333;
    }
    /* 注册和找回密码按钮样式 */
    :is(.buttons) :is(.secondary-button) {
        background-color: #f0f0f0;
        color: #333;
        margin-bottom: 10px;
    }
    :is(.buttons) :is(.secondary-button):hover {
        background-color: #eaeaea;
    }

    /* 下拉菜单样式 */
    .myDropdown{
        position: fixed;
        top: 20px;
        right: 10px;
        z-index: 1000;

        display: inline-block;
        float:left;
    }
    .myDropdown-content{
        right: 0;
        top: 60px;

        position: absolute;
        background-color: #f9f9f9;
        min-width: 160px;
        box-shadow:  0px 8px 16px 0px rgba(0,0,0,0.2);

        opacity: 0;
        transition: opacity 0.3s ease-in-out;
        right: 0; /* 与头像悬浮窗对齐 */
        top: 60px; /* 位于头像悬浮窗外部 */
    }
    .myDropdown-content a{
        color: #000000;
        padding: 12px 16px;
        text-decoration: none;
        display: block;
    }
    .myDropdown-content a:hover{background-color: #f1f1f1}
    .myDropdown:hover .myDropdown-content{
        display: block;
        opacity: 100;
        transition: opacity 0.3s ease-in-out;
    }
    .myDropdown:hover .dropbtn{
        background-color: #a1a1a1;
    }

    /* 屏幕宽度<992px时的样式 */
    @media (max-width: 992px) {
        .myDropdown {
            position: fixed;
            top: 20px;
            right: 10px;
        }
    }

    /* 屏幕宽度992px-1200px时的样式 */
    @media (min-width: 992px) and (max-width: 1200px) {
        .myDropdown {
            position: fixed;
            top: 60px;
            right: 10px;
        }
    }
</style>

<script>
    document.getElementById('loginForm').addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为
        const email = document.getElementById('email').value;
        const password = document.getElementById('password').value;
        login(email, password); // 调用登录函数
    });

    function reversibleHash4to6(str) {
        const primeMultiplier = 7;
        const offset = 100000;
        const num = parseInt(str, 10);
        const hash = ((num * primeMultiplier) + offset) % 1000000;
        return hash.toString().padStart(6, '0');
    }
    function reversibleHash6to4(hashStr) {
        const primeMultiplier = 7;
        const offset = 100000;
        const hash = parseInt(hashStr, 10);
        const original = ((hash - offset) / primeMultiplier) | 0;
        return original.toString().padStart(4, '0');
    }

    // 显示加载遮罩层
    function showLoadingOverlay() {
        const overlay = document.createElement('div');
        overlay.style.position = 'fixed';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.width = '100%';
        overlay.style.height = '100%';
        overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
        overlay.style.display = 'flex';
        overlay.style.justifyContent = 'center';
        overlay.style.alignItems = 'center';
        overlay.style.zIndex = '9999';

        const loadingText = document.createElement('div');
        loadingText.style.color = 'white';
        loadingText.style.fontSize = '20px';
        //loadingText.textContent = 'Operation in progress\nPlease wait';
        loadingText.innerHTML = 'Operation in progress...<br><br>Please wait';

        overlay.appendChild(loadingText);
        document.body.appendChild(overlay);
    }
    // 隐藏加载遮罩层
    function hideLoadingOverlay() {
        const overlay = document.querySelector('div[style*="position: fixed; top: 0; left: 0; width: 100%; height: 100%;"]');
        if (overlay) {
            document.body.removeChild(overlay);
        }
    }


    // 假设你的API密钥和Supabase URL配置
    //const supabaseURL = 'https://cnlchrq5g6hen2t5llr0.baseapi.memfiredb.com';
    const supabaseURL = 'https://dshmbsawwrbuycnivcjs.supabase.co';
    //const supabaseAPIKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImV4cCI6MzI4NjY4NTY3OSwiaWF0IjoxNzA5ODg1Njc5LCJpc3MiOiJzdXBhYmFzZSJ9.Y3loZqk0iqgFwofs_Sa107YheczRlttX_ZTOMboaf7c';
    const supabaseAPIKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRzaG1ic2F3d3JidXljbml2Y2pzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTM5Mjg2OTAsImV4cCI6MjA2OTUwNDY5MH0.fwRJD-WuST7mCbJf9h2i2Xk0z6mtCMCeV--JGUecC6A';

    let userToken = ''; // 用于存储用户的access_token
    let userId = ''; // 用于存储用户的user_id


    // 函数：邮箱/密码登录
    function login(email, passwd) {
      showLoadingOverlay(); // 加载遮罩层
      const password = reversibleHash4to6(passwd);
      fetch(`${supabaseURL}/auth/v1/token?grant_type=password`, {
        method: 'POST',
        headers: {
          'apikey': supabaseAPIKey,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email, password })
      })
      .then(response => response.json())
      .then(data => {
        console.log(data);
        if (data.access_token) {
            // 登录成功
            userToken = data.access_token; // 存储access_token
            userId = data.user.id; // 存储user_id
            // 改为不设置httpOnly;
            //document.cookie = `access_token=${userToken}; path=/; secure; httpOnly;`; // 设置cookie
            document.cookie = `access_token=${userToken}; path=/; secure;`;
            document.cookie = `user_id=${userId}; path=/; secure;`; // 设置user_id cookie
            console.log('Cookie has been set. Cookie content:', getCookie('access_token'), getCookie('user_id')); // 打印cookie内容
            // 登录成功后刷新页面
            alert('Login success! Please click OK to continue.');
            // 用户点击确定后刷新页面
            window.location.reload();
        } else {
            // 登录失败
            console.error('Login failed:', data);
            // 错误提示，弹出一个警告框
            alert('Login failed: ' + data.error_description);
        }
    })
    .catch(error => {
        hideLoadingOverlay(); // 隐藏加载遮罩层
        console.error('Error:', error);
        //错误提示，弹出一个警告框
        alert('An error occurred during login.');
    });
}

    // 函数：登出用户
    function logout() {
      showLoadingOverlay(); // 加载遮罩层
      userToken = getCookie('access_token');
      // 发送登出请求
      fetch(`${supabaseURL}/auth/v1/logout`, {
        method: 'POST',
        headers: {
          'apikey': supabaseAPIKey,
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${userToken}` // 使用存储的用户token
        }
      })
      .then(data => {
        console.log(data);
        // 登出成功后清除cookie
        userToken = ''; // 清除用户token
        userId = ''; // 清除用户user_id
        document.cookie = 'access_token=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT; secure;'; // 清除cookie
        document.cookie = 'user_id=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT; secure;'; // 清除user_id cookie
        console.log('Cookie has been cleared.'); // 打印清除cookie的信息
        hideLoadingOverlay(); // 隐藏加载遮罩层
        // 登出成功后刷新页面
        window.location.reload();
      })
      .catch(error => {
        hideLoadingOverlay(); // 隐藏加载遮罩层
        console.error('Error:', error);
        alert('An error occurred during logout.'); // 提示用户登出失败
      });
    }

    // 函数：获取用户信息
    function getUserInfo() {
      const token = getCookie('access_token'); // 从cookie中获取access_token
      fetch(`${supabaseURL}/auth/v1/user`, {
        method: 'GET',
        headers: {
          'apikey': supabaseAPIKey,
          'Authorization': `Bearer ${token}` // 使用存储的用户token
        }
      })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    }

    // 函数：发送忘记密码邮件
    function recoverPassword(email) {
      fetch(`${supabaseURL}/auth/v1/recover`, {
        method: 'POST',
        headers: {
          'apikey': supabaseAPIKey,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email })
      })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    }

    // 函数：更新用户信息
    function updateUser(email, password, userData) {
      const token = getCookie('access_token'); // 从cookie中获取access_token
      fetch(`${supabaseURL}/auth/v1/user`, {
        method: 'PUT',
        headers: {
          'apikey': supabaseAPIKey,
          'Authorization': `Bearer ${token}`, // 使用存储的用户token
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email, password, data: userData })
      })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    }

    // 函数：通过邮件发送邀请
    function inviteUser(email) {
      fetch(`${supabaseURL}/auth/v1/invite`, {
        method: 'POST',
        headers: {
          'apikey': supabaseAPIKey,
          'Authorization': `Bearer ${supabaseAPIKey}`, // 使用service_role_key
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email })
      })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    }

    // 函数：获取cookie
    function getCookie(name) {
      let cookieArray = document.cookie.split(';');
      for (let i = 0; i < cookieArray.length; i++) {
        let cookie = cookieArray[i].trim();
        if (cookie.indexOf(name + "=") == 0) {
          return cookie.substring(name.length + 1, cookie.length);
        }
      }
      return "";
    }
</script>

<!-- 头像悬浮窗 -->
<div class="myDropdown">
    <img class="avatar-floating-window dropbtn" src="./assets/images/def-profile-gray.png" alt="User Avatar">
    <div class="myDropdown-content">
        <a href="#" onclick="logout()">Logout</a>
        <a href="#" onclick="window.location.href='./messageBoard/user_conf/registerUser.html';">Register</a>
        <a href="#" onclick="window.location.href='./messageBoard/user_conf/login.html';">Switch Account</a>
        <a href="#" onclick="window.location.href='./messageBoard/user_conf/uploadProfile.html';">Upload Profile</a>
        <a href="#" onclick="window.location.href='./messageBoard/user_conf/userListWithProfile_fromed.html#';">User List</a>
    </div>
</div>

<!-- 登录弹窗 -->
<div id="loginModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <form id="loginForm">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required><br><br>
            <label for="password">Password(PIN):</label>
            <input type="password" id="password" name="password" required><br><br>
            <div class="buttons">
                <button type="button" onclick="login(document.getElementById('email').value, document.getElementById('password').value)">Login</button>
                <button type="button" class="secondary-button" onclick="window.location.href='./messageBoard/user_conf/registerUser.html';">Register</button>
                <button type="button" class="secondary-button" onclick="window.location.href='';">Forgot Password</button>
            </div>
        </form>
    </div>
</div>

<script>
    // 获取头像悬浮窗元素
    var avatarFloatingWindow = document.querySelector('.avatar-floating-window');
    var initialTop = 8; // 初始的top值
    var movedUp = false; // 是否已经向上移动过
    var dropdownContent = document.querySelector('.myDropdown-content');


    // 监听滚动事件
    window.addEventListener('scroll', function() {
        var scrollHeight = window.pageYOffset || document.documentElement.scrollTop;
        var currentTop = parseInt(window.getComputedStyle(avatarFloatingWindow).top, 5);
        var isNarrowScreen = window.innerWidth < 1200 && window.innerWidth > 992; // 检查屏幕宽度

        if (scrollHeight > 0 && !movedUp && !isNarrowScreen) { // 当页面向下滚动且还没有向上移动过
            avatarFloatingWindow.style.top = (initialTop - 5) + 'px'; // 计算新的top值，平滑减少5px
            movedUp = true; // 标记为已经向上移动过
        } else if (scrollHeight === 0 && movedUp && !isNarrowScreen) { // 当页面向上滚动回到顶部
            avatarFloatingWindow.style.top = initialTop + 'px'; // 恢复到初始的top值
            movedUp = false; // 重置标记
        }
    });

    // 获取弹窗元素
    var modal = document.getElementById("loginModal");
    var span = document.getElementsByClassName("close")[0];
    var modalContent = document.querySelector('.modal-content');
    // 显示弹窗
    function showModal() {
        modal.style.display = "block";
        modalContent.classList.add('show');
    }
    // 隐藏弹窗
    function hideModal() {
        modal.style.display = "none";
        modalContent.classList.remove('show');
    }
    // 处理头像点击事件
    avatarFloatingWindow.addEventListener('click', function() {
        if (isLoggedIn()) {
            // 如果已登录，不执行任何操作
        } else {
            // 如果未登录，显示登录弹窗
            showModal(); //TODO：不使用登录弹窗?
            // window.location.href = 'login.html';
        }
    });
    // 点击 <span> (x) 时关闭弹窗
    span.onclick = function() {
        hideModal();
    }
    // 点击窗口外的区域时关闭弹窗
    window.onclick = function(event) {
        if (event.target == modal) {
            hideModal();
        }
    }
</script>

<script>

    // 获取头像信息的函数
    function fetchUserProfile头像() {
        const userId = getCookie('user_id'); // 从cookie中获取user_id
        if (!userId) {
            console.log('No user_id found in cookies.');
            return;
        }

        fetch(`${supabaseURL}/rest/v1/user_profile?user_id=eq.${userId}`, {
            method: 'GET',
            headers: {
                'apikey': supabaseAPIKey
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.length > 0 && data[0].data) {
                updateAvatar(data[0].data);
            } else {
                console.log('No avatar URL found for the user.');
            }
        })
        .catch(error => console.error('Error fetching user profile:', error));
    }

    // 更新头像显示的函数
    function updateAvatar(avatarData) {
        const avatarImg = document.querySelector('.avatar-floating-window');
        avatarImg.src = avatarData; // 设置src为Base64数据
    }

    // 页面加载完成后获取用户信息并更新头像
    window.addEventListener('load', fetchUserProfile头像);


    // 检查用户是否登录的函数
    function isLoggedIn() {
        return getCookie('access_token') !== '';
    }

    // 显示弹窗的函数
    function showModal() {
        var modal = document.getElementById("loginModal");
        var modalContent = document.querySelector('.modal-content');
        modal.style.display = "block";
        modalContent.classList.add('show');
    }

    // 隐藏弹窗的函数
    function hideModal() {
        var modal = document.getElementById("loginModal");
        modal.style.display = "none";
        document.querySelector('.modal-content').classList.remove('show');
    }

    // 页面加载完成后检查用户登录状态并更新头像悬浮窗和下拉菜单的显示
    window.addEventListener('load', function() {
        if (!isLoggedIn()) {
            dropdownContent.style.display = 'none'; // 未登录时隐藏下拉菜单
        } else {
            dropdownContent.style.display = 'block'; // 登录时显示下拉菜单
        }
        fetchUserProfile头像(); // 获取用户信息并更新头像
    });
</script>